package org.tinaelle.hibernate.audit;

import java.util.HashMap;
import java.util.Iterator;

import org.tinaelle.ServiceLocator;
import org.tinaelle.common.criteria.AdTableSearchCriteria;
import org.tinaelle.common.dto.AdChangeLogDTO;
import org.tinaelle.common.dto.AdTableDTO;
import org.tinaelle.common.dto.SearchDataResultDTO;
import org.tinaelle.server.domain.AdChangeLog;
import org.tinaelle.server.domain.AdTable;
import org.tinaelle.utils.Session;

/**
 * DOCUMENT ME!
 * 
 * @author $author$
 * @version $Revision$
 */
public class DatabaseActionLogger implements ActionLogger {
	HashMap<String, AdTableDTO>	tables;

	public AdTableDTO getTable(final String tableName) {
		if ( tables == null ) {
			final SearchDataResultDTO allTables = ServiceLocator.instance().getAdSystemService().findByCriteria(
			        new AdTableSearchCriteria() );
			tables = new HashMap<String, AdTableDTO>();
			for ( final Iterator<?> i = allTables.getResult().iterator(); i.hasNext(); ) {
				final AdTableDTO oneTable = ( AdTableDTO ) i.next();
				tables.put( oneTable.getTableName(), oneTable );
			}
		}
		return tables.get( tableName );
	}

	/**
	 * DOCUMENT ME!
	 * 
	 * @param command
	 *            DOCUMENT ME!
	 * @param entity
	 *            DOCUMENT ME!
	 * @param properties
	 *            DOCUMENT ME!
	 * @param userId
	 *            DOCUMENT ME!
	 */
	public void logThis(final String command, final Object entity, final String[] properties, final Long userId) {
		System.err.println( "logThis : " + entity.getClass().getName() + ", " + command );

		if ( !( entity instanceof AdChangeLog ) && !( entity instanceof AdTable ) ) {
			// prse object, get all the methods
			final ParseHibEntity phe = new ParseHibEntity( entity, properties );

			final AdTableDTO adTableDTO = getTable( phe.extractTableName() );

			if ( !adTableDTO.isIsChangeLog() ) {
				return;
			}

			// new actionlog
			final AdChangeLogDTO actionLog = new AdChangeLogDTO();

			// set command and table name
			actionLog.setCommand( command );

			actionLog.setRecordId( phe.extractPrimaryKeyValue() );
			actionLog.setAdTableId( adTableDTO.getAdTableId() );
			actionLog.setAdSessionId( Session.get().getSession().getAdSessionId() );

			// save all contact values
			actionLog.setConcatValues( phe.extractColumnValues() );

			ServiceLocator.instance().getAdSystemService().save( actionLog );
		} // end if
	} // end logThis()
} // end DatabaseActionLogger
